import React, { Component } from 'react';
import { connect } from 'react-redux';
import '../../resources/styles/Login.css';

const trim = str => String.prototype.trim.call(str);

class Register extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username:'',
      email: '',
      password: '',
      repeat: ''
    }
    this.handleRegister = this.handleRegister.bind(this);
  }

  handleRegister() {
    
    const { username, email, password, repeat } = this.state;
    if(!username || !email || !password || !repeat){
      alert('表单填写不完整');
      return;
    }
    if (trim(password) !== trim(repeat)){
      alert('两次输入的密码不一样!');
      return;
    }
    this.props.dispatch({
      type: '$register',
      param: {
        username,
        email,
        password
      }
    })
  }

  render() {
    return (
      <div className="signin">
        <div className="signin-form">
          <div className="signin-form-title">
            注册
          </div>
          <div className="signin-form">
            <input
              type="text"
              placeholder="请输入真实姓名"
              onChange={e => this.setState({ username: e.target.value })}
              value={this.state.username} />
            <input
              type="email"
              placeholder="请输入你的公司邮箱"
              onChange={e => this.setState({ email: e.target.value })}
              value={this.state.email} />
            <input
              type="password"
              placeholder="请输入密码"
              onChange={e => this.setState({ password: e.target.value })}
              value={this.state.password} />
            <input
              type="password"
              placeholder="请重复你的密码"
              onChange={e => this.setState({ repeat: e.target.value })}
              value={this.state.repeat} />
            <div
              className="btn primary"
              onClick={this.handleRegister}>注册</div>
            <div
              className="btn secondary"
              onClick={() => this.props.history.push('/login')}>返回登录</div>
          </div>
        </div>
      </div>
    );
  }
}

export default connect(state => state)(Register);
